<template>
  <div>
    <div class="dialog_div">
      <el-dialog :visible.sync="dialogVisible" lock-scroll width="50%">
        <div slot="title" class="header_title">
          <span class="title_span">批量导入图片</span>
        </div>
        <div class="content_div">
          <div class="content">
            <div class="title">
              <p>支持图片名称与商品名称匹配进行导入，如：</p>
              <p>商品名称：苹果，</p>
              <p>图片名称：苹果-1，苹果-2，苹果-3，...以此类推，导入后自动排序。</p>
            </div>
            <div>
              <p>1、选择导入方式</p>
              <div style="display: flex; align-items: center; justify-content: space-between">
                <el-radio v-model="radio" label="1">保留原图片，增加新图片</el-radio>
                <el-radio v-model="radio" label="2">覆盖原图片，替换成新图片</el-radio>
              </div>
            </div>
            <div style="margin-top: 40px">
              <p>
                2、导入图片文件
                <span style="color: #999; font-size: 12px"
                  >(支持zip，最大500M，单张图片不超过2M，每个商品限制10张图片)</span
                >
              </p>
              <div style="margin: 15px 0 40px 0; display: flex; align-items: center; height: 30px">
                <el-upload
                  ref="upload"
                  class="uploader"
                  accept=".zip"
                  :disabled="fileName ? true : false"
                  :limit="1"
                  :action="uploadAction"
                  :headers="headers"
                  :data="{ isOverwrite: radio === '1' ? false : true, accountBookId: accountBook, uuid: file.uid }"
                  :on-change="handleChange"
                  :on-success="handleSuccess"
                  :on-progress="handleProgress"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :auto-upload="false"
                >
                  <el-button size="small" type="primary" :class="fileName ? 'disabled_button' : ''"
                    >上传压缩文件</el-button
                  >
                </el-upload>
                <div style="display: flex; align-items: center; height: 30px">
                  <span style="margin-left: 10px; color: #1a93fa">{{ fileName }}</span>
                  <img
                    v-if="fileName"
                    src="@/assets/shop/del.png"
                    @click="deleteFile"
                    style="width: 12px; height: 12px; margin-left: 10px; align-self: start; cursor: pointer"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="footer_div">
            <div style="padding: 30px 0; border-top: 1px solid #eeeeee">
              <el-button type="primary" @click="submit()" :loading="importLoading">导入</el-button>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
    <div class="dialog_div_tip">
      <el-dialog
        :visible.sync="dialogVisibleTip"
        :show-close="false"
        width="34%"
        :before-close="handleCloseTip"
        :title="tipData.title"
      >
        <div class="content_div">
          <div v-if="tipData.status === 'uploading'" class="info_div">
            <p>共上传1个压缩包</p>
            <p>正在上传中,请勿关闭</p>
          </div>
          <div v-if="tipData.status === 'complete'" class="info_div">
            <p>匹配成功{{ tipData.successCount }}个文件</p>
            <p style="color: #ff0000">匹配失败{{ tipData.failedCount }}个</p>
            <div style="overflow-y: auto; max-height: 100px" class="failed_files">
              <p v-for="(value, key) in tipData.failedFiles" :key="key">{{ key }}: {{ value }}</p>
            </div>
            <el-button type="text" style="color: #004cff" @click="handleCloseTip">继续上传</el-button>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <div v-if="tipData.status === 'uploading'" style="margin-top: 50px">
            <el-button type="text" style="color: #333333" @click="closeUpload">取消上传</el-button>
          </div>
          <div v-else style="width: 100%">
            <el-button type="text" style="color: #333333" @click="handleCloseTip">取消</el-button>
            <el-button type="text" style="color: #333333" @click="handleCloseTip">确定</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { getAction, putAction, postAction } from '@/api/manage'
import * as xlsx from 'xlsx'
import { axios } from '@/utils/request'
import { delcommafy, accSub, accAdd, accMul, formatMoney } from '@/utils/index'

import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID, ACCOUNT_BOOK, SAMPLE_FLAG } from '@/store/mutation-types'

export default {
  name: 'BasicInformation',
  props: ['titles', 'storehouseId', 'url', 'isGoods'],
  computed: {
    ...mapGetters(['name']),
  },
  created() {
    this.load()
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        Object.assign(this.$data, this.$options.data())
        this.uploadAction = window._CONFIG['domianURL'] + this.url
        this.dialogVisible = true
        this.load()
      }
    },
  },
  data() {
    return {
      uploadAction: window._CONFIG['domianURL'] + '/goods/yoshopGoods/importImgBatch',
      headers: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) },
      accountBook: Vue.ls.get(ACCOUNT_BOOK).id,
      radio: '1',
      fileName: '',
      dialogVisible: false,
      importLoading: false,
      file: {},
      fileName: '',
      dialogVisibleTip: false,
      tipData: {
        status: '',
        title: '',
        successCount: 0,
        failedCount: 0,
        failedFiles: [],
      },
    }
  },
  methods: {
    // 关闭提示弹窗并将之前传过的文件清除
    handleCloseTip() {
      this.dialogVisibleTip = false
      this.fileName = ''
      this.file = {}
      this.$refs.upload.clearFiles()
    },
    // 取消上传
    closeUpload() {
      console.log('取消上传file', this.file)
      this.dialogVisibleTip = false
      postAction('/goods/yoshopGoods/cancelImportImgBatch', { accountBookId: this.accountBook, uuid: this.file.uid }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
      this.$refs.upload.abort(this.file) //取消上传请求 file: fileList 中的 file 对象
      this.fileName = ''
      this.file = {}
      this.$refs.upload.clearFiles()
    },
    // 上传中
    handleProgress(e, file, fileList) {
      console.log('e', e)
      console.log('file', file)
      console.log('fileList', fileList)
      // 触发父组件上传中提示
      this.tipData = {
        status: 'uploading',
        title: '上传中提示',
        successCount: 0,
        failedCount: 0,
        failedFiles: [],
      }
      this.dialogVisibleTip = true
    },
    // 上传状态该改变
    handleChange(file, fileList) {
      // console.log("file",file)
      // console.log("fileList",fileList)
      this.file = file
      this.fileName = file.name
    },
    // 上传前
    beforeUpload(file) {
      console.log('上传前file', file)
      const isZip = file.type === 'application/x-zip-compressed' || file.name.endsWith('.zip')
      const isLt500M = file.size / 1024 / 1024 < 500

      if (!isZip) {
        this.$message.error('请上传zip格式的压缩文件!')
        return false
      }
      if (!isLt500M) {
        this.$message.error('上传文件大小不能超过 500MB!')
        return false
      }
      return true
    },
    // 文件上传成功
    handleSuccess(response, file, fileList) {
      console.log('上传成功response', response)
      console.log('上传成功file', file)
      console.log('上传成功fileList', fileList)
      if (response.success) {
        this.tipData.status = 'complete'
        this.tipData.title = response.result.failedCount > 0 ? '匹配失败提示' : '匹配成功完成'
        this.tipData.successCount = response.result.successCount
        this.tipData.failedCount = response.result.failedCount
        this.tipData.failedFiles = response.result.failedFiles
      }
    },
    // 删除文件
    deleteFile() {
      this.fileName = ''
      this.file = {}
      this.$refs.upload.clearFiles()
    },
    load() {
      // var titleList = Object.values(this.titles)
      // for (var i = 0; i < titleList.length; i++) {
      //   if (titleList[i].zidingyiState) {
      //     const obj = {
      //       index: i + 1,
      //       isRequired: titleList[i].isRequired,
      //       morenName: titleList[i].zidingyiName ? titleList[i].zidingyiName : titleList[i].morenName,
      //       props: titleList[i].props,
      //       keyName: '',
      //     }
      //     this.jsonObject.push(obj)
      //   }
      // }
    },
    submit() {
      if (!this.fileName) {
        this.$message.error('请上传压缩文件')
        return
      }
      this.$refs.upload.submit()
    },
  },
}
</script>

<style lang="scss" scoped>
.disabled_button {
  background: #cbced3 !important;
  color: #666 !important;
  cursor: not-allowed;
  border: none;
}
.dialog_div {
  ::v-deep .el-dialog {
    width: 100%;
    padding: 0 70px;
    .el-dialog__body {
      padding: 0;
    }
    .el-dialog__header {
      width: 100%;
      height: 0.937559rem;
      box-sizing: border-box;
      padding: 0 0.187512rem 0 0.281268rem;
      border-bottom: 1px solid #eeeeee;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .el-dialog__headerbtn {
        position: static;
        .el-icon-close {
          color: #999;
          font-size: 0.48753rem;
        }
      }
    }
  }
  ::v-deep .el-button {
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    // font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    // color: #666;
  }
  .content_div {
    .content {
      .title {
        width: 100%;
        padding: 20px;
        background: #e6f7ff;
        margin: 20px 0;
        p {
          font-weight: 600;
          font-size: 14px;
          color: #0071d1;
          line-height: 15px;
        }
      }
    }
  }
}
.dialog_div_tip {
  ::v-deep .el-dialog {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    // padding: 50px 90px 20px;
    .el-dialog__header {
      padding-top: 40px;
      justify-content: center;
      border-bottom: none;
      .el-dialog__title {
        font-weight: 400;
        font-size: 16px;
        color: #ff820d;
      }
    }
    .el-dialog__body {
      // padding: 36px 90px 20px;
    }
    .el-dialog__footer {
      width: 100%;
      // padding: 10px 90px 20px;
      div {
        display: flex;
        align-items: center;
        justify-content: space-around;
      }
    }
    .failed_files {
      font-weight: 400;
      font-size: 11px;
      color: #333333;
    }
  }
  .content_div {
    .info_div {
      font-weight: 400;
      font-size: 16px;
      color: #0e2135;
    }
  }
}
</style>
